import * as _ from 'lodash';

import { logger } from '$common';
import { Storage } from '$infra';
import { BufferFlusher, FlushOptions } from '$domain/service/bufferFlusher';
export class StorageLogFlusher {

  private bFlusher: BufferFlusher;

  constructor(private storageFilePath: string, flushOptions?: FlushOptions) {
    this.bFlusher = new BufferFlusher(flushOptions);
    this.bFlusher.on('flush', this.onFlush);
  }

  onFlush = async (logItems: string[]) => {
    if (_.isEmpty(logItems)) { return; }

    logger.debug(`⬇ StorageLogFlusher ==> append log to ${this.storageFilePath}`);

    try {
      const joinWithLineBreak = logItems.reduce((acc, cur) => {
        acc += `${cur}\r\n`;
        return acc;
      }, '');

      await Storage.Instance.append(this.storageFilePath, joinWithLineBreak);
    } catch (e) {
      logger.warn(`write log to storage failed ${e}`);
    }
  };

  add(content: string) {
    this.bFlusher.add(content);
  }

  flush() {
    this.bFlusher.flush();
  }
}